package com.efounder.news.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.mobilenews.R;
import com.efounder.news.adapter.DetailCommentAdapter;
import com.efounder.news.bean.CommentListBean;
import com.efounder.news.bean.CommentReplyBean;
import com.efounder.news.http.Api;
import com.efounder.news.http.DataParse;
import com.efounder.news.http.NewsRequestManager;
import com.efounder.news.irecyclerview.IRecyclerView;
import com.efounder.news.irecyclerview.OnLoadMoreListener;
import com.efounder.news.utils.LogUtils;
import com.efounder.news.view.CommentDialog;
import com.efounder.news.view.LoadMoreFooterView;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommentDetailActivity extends BaseActivity {


    private ImageView ivShare;
    private TextView tvAuthor;
    private TextView tvName;
    private TextView tvComment;
    private TextView tvTime;
    private TextView tvReply;
    private ImageView ivAvatar;
    private RelativeLayout tvWrite;
    private TextView commentSign;
    /**
     * 银钻icon
     */
    private ImageView ivNewsCommentIconJifen;
    /**
     * 银钻积分
     */
    private TextView tvNewsCommentJifen;
    /**
     * 点赞
     */
    private TextView tvLikeCount;
    private IRecyclerView commentListView;
    private LoadMoreFooterView mLoadMoreFooterView;
//    private View commentHeaderView;

    private DetailCommentAdapter mDetailCommentAdapter;

    //    private List<CommentReplyBean> mCommentList;
//    private List<CommentReplyBean> moreComments;
    private List<CommentReplyBean> mList = new ArrayList<>();
    private CommentListBean mCommentListBean;
    private CommentReplyBean mCommentReplyBean;

    private User mUser;

    private int commentPage = 1;

    private String newId;
    private String parentCommentId;
    private String userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_detail);

//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//            Slide slide = new Slide();
//            slide.setDuration(200);
//            getWindow().setEnterTransition(slide);
//        }

        Intent intent = getIntent();

        mCommentListBean = (CommentListBean) intent.getSerializableExtra("commentBean");
        mUser = (User) intent.getSerializableExtra("user");

//        newId = mCommentListBean.getNewsId();
        newId = intent.getStringExtra("newsId");
        parentCommentId = mCommentListBean.getCommentId();

        LogUtils.d(TAG, mCommentListBean.toString());

        initTopEndView();
        initView();
        bindData();
        getCommentData();
        initListener();
    }


    private void initTopEndView() {
        ivShare = (ImageView) findViewById(R.id.iv_share);
        tvAuthor = (TextView) findViewById(R.id.tv_author);
        ivShare.setVisibility(View.INVISIBLE);
        LinearLayout leftBackImg = (LinearLayout) findViewById(R.id.iv_back);
        leftBackImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tvWrite = (RelativeLayout) findViewById(R.id.tv_comment);
        tvWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommentDialog(ResStringUtil.getString(R.string.detail_write_comment));
            }
        });
    }

    private void initView() {
//        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        ivNewsCommentIconJifen = (ImageView) findViewById(R.id.iv_news_comment_icon_jifen);
        tvNewsCommentJifen = (TextView) findViewById(R.id.tv_news_comment_jifen);
        tvLikeCount = (TextView) findViewById(R.id.tv_like_count);

        commentListView = (IRecyclerView) findViewById(R.id.rl_comment);
        commentListView.setLayoutManager(new LinearLayoutManager(this));

        mLoadMoreFooterView = (LoadMoreFooterView) commentListView.getLoadMoreFooterView();
//        commentHeaderView = layoutInflater.inflate(R.layout.comment_list_header, null);
//        commentListView.addHeaderView(commentHeaderView);

        tvName = (TextView) findViewById(R.id.tv_name);
        tvComment = (TextView) findViewById(R.id.tv_comment_detail);
        tvTime = (TextView) findViewById(R.id.tv_comment_time);
        tvReply = (TextView) findViewById(R.id.tv_reply);
        commentSign = (TextView) findViewById(R.id.comment_sign);
        ivAvatar = (ImageView) findViewById(R.id.iv_detail_avatar);

        isSupportIntegral();
    }



    private void bindData() {
        tvName.setText(mCommentListBean.getUserName());
        tvComment.setText(mCommentListBean.getComment());
        tvTime.setText(mCommentListBean.getCommentDate());
        tvLikeCount.setText(mCommentListBean.getDiggCount());
        tvNewsCommentJifen.setText(CommentDetailActivity.this.getString(R.string.news_comment_add_silver_drill,mCommentListBean.getIntegral()));
        setNetPicture(Api.getAvator + mCommentListBean.getUserId(), ivAvatar);

        isLike();
    }

    /**
     * 加载评论数据
     */
    private void getCommentData() {
        mList.clear();
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", String.valueOf(mUser.getId()));
        map.put("showPage", "1");
        map.put("pageNum", "5");
        map.put("parentcommentid", parentCommentId);
        LoadingDataUtilBlack.show(CommentDetailActivity.this);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadCommentReply/" + newId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        commentSign.setText(R.string.detail_write_comment_first);

                        mDetailCommentAdapter = new DetailCommentAdapter(CommentDetailActivity.this, mList);
                        commentListView.setIAdapter(mDetailCommentAdapter);
                        mDetailCommentAdapter.setOnItemClickListener(new DetailCommentAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
                                mCommentReplyBean = mList.get(position);
//                                LogUtils.i(TAG, mCommentReplyBean.getId());
                                String str = ResStringUtil.getString(R.string.detail_reply) + " " + mCommentReplyBean.getUserName() + ":";
                                replyCommentDialog(mCommentReplyBean.getId(), str);
                            }
                        });
                        mDetailCommentAdapter.setOnGoodClickListener(new DetailCommentAdapter.OnGoodClickListener() {
                            @Override
                            public void onGoodClick(int position) {
//                                LogUtils.d(ResStringUtil.getString(R.string.detail_dianzan), mList.get(position).getText());
                                like("1", mList.get(position).getId(), position);
                            }
                        });
                        mDetailCommentAdapter.setOnBadClickListener(new DetailCommentAdapter.OnBadClickListener() {
                            @Override
                            public void onBadClick(int position) {
//                                LogUtils.d(ResStringUtil.getString(R.string.detail_dianzan), mList.get(position).getText());
                                like("0", mList.get(position).getId(), position);
                            }
                        });

                        List<CommentReplyBean> mCommentList = DataParse.getCommentReply(result);

                        if (mCommentList != null) {
                            mList.addAll(mCommentList);
                            commentSign.setText(R.string.detail_all_comment);


                        }
//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        LogUtils.d(TAG, errorMsg);
                        LoadingDataUtilBlack.dismiss();
                    }
                });
    }

    /**
     * 监听上拉加载和下拉刷新
     */
    private void initListener() {


        commentListView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (mLoadMoreFooterView.canLoadMore() && mDetailCommentAdapter.getItemCount() > 0) {
                    pullUpToLoad();
                }
            }
        });
        /**
         * 点赞按钮点击事件
         */
        tvLikeCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //防止多次点击
                tvLikeCount.setEnabled(false);
                if (mCommentListBean.getUserDigg().equals("0")) {
                    like("1",mCommentListBean.getCommentId(),0);
                } else {
                    like("0",mCommentListBean.getCommentId(),0);
                }
            }
        });
    }

    /**
     * 上拉加载更多
     */
    private void pullUpToLoad() {
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);
        commentPage += 1;
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", String.valueOf(mUser.getId()));
        map.put("showPage", String.valueOf(commentPage));
        map.put("pageNum", "5");
        map.put("parentcommentid", parentCommentId);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadCommentReply/" + newId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        List<CommentReplyBean> moreComments = DataParse.getCommentReply(result);
                        if (moreComments.size() == 0) {
                            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
                            commentListView.setRefreshing(false);
                        } else {
                            mList.addAll(moreComments);
                            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
                        }
                        mDetailCommentAdapter.notifyDataSetChanged();
//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        LogUtils.d(TAG, errorMsg);
                        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.ERROR);
                    }
                });
    }

    /**
     * 点赞或取消赞
     *
     * @param digg
     * @param commentId
     */
    private void like(final String digg, String commentId, final int postion) {

        String userId = String.valueOf(mUser.getId());
        String nickName = mUser.getNickName();

        Map<String, String> map = new HashMap<>();
        map.put("commentid", commentId);
        map.put("user", userId);
        map.put("username", nickName);
        map.put("digg", digg);
        LoadingDataUtilBlack.show(CommentDetailActivity.this);

        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/diggComment/" + newId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        tvLikeCount.setEnabled(true);
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if(jsonObject.optString("message").equals("success")){
                                //判断当前是否点赞，处理点赞数量
                                int dCount = Integer.parseInt(mCommentListBean.getDiggCount());
                                if(digg.equals("1")){

                                    dCount += 1;
                                    String diggCount = String.valueOf(dCount);
                                    mCommentListBean.setUserDigg("1");
                                    mCommentListBean.setDiggCount(diggCount);
                                    tvLikeCount.setText(diggCount);
                                }else {
                                    dCount -= 1;
                                    String diggCount = String.valueOf(dCount);
                                    mCommentListBean.setUserDigg("0");
                                    mCommentListBean.setDiggCount(diggCount);
                                    tvLikeCount.setText(diggCount);
                                }
                                //切换点赞图片
                                isLike();
                                //获取积分
                                int integral = jsonObject.optInt("integral");
                                mCommentListBean.setIntegral(integral+"");
                                tvNewsCommentJifen.setText(CommentDetailActivity.this.getString(R.string.news_comment_add_silver_drill,integral));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        LogUtils.d(TAG +ResStringUtil.getString( R.string.detail_dianzan_or_cancle), result);
//                        mCommentAdapter.notifyDataSetChanged();
//                        mDetailCommentAdapter.notifyItemChanged(postion);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        tvLikeCount.setEnabled(true);
                        LoadingDataUtilBlack.dismiss();
//                        Toast.makeText(CommentDetailActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
//                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }


    /**
     * 弹出评论Dialog
     */
    private void showCommentDialog(String str) {
        new CommentDialog(str, new CommentDialog.SendListener() {
            @Override
            public void sendComment(String inputText) {
                postComment(inputText);
            }
        }).show(getSupportFragmentManager(), "comment");
    }

    /**
     * 回复评论的评论的Dialog
     *
     * @param str
     */
    private void replyCommentDialog(final String replyId, String str) {
        new CommentDialog(str, new CommentDialog.SendListener() {
            @Override
            public void sendComment(String inputText) {
                postReplyComment(replyId, inputText);
            }
        }).show(getSupportFragmentManager(), "comment");
    }

    /**
     * 发送评论
     *
     * @param comment
     */
    private void postComment(String comment) {

        String userId = String.valueOf(mUser.getId());
        String nickName = mUser.getNickName();
        String parentCommentId = mCommentListBean.getCommentId();
        String newsId = newId;

        Map<String, String> map = new HashMap<>();
//        map.put("newsid", newsId);
        map.put("user", userId);
        map.put("username", nickName);
        map.put("comment", comment);
        map.put("parentcommentid", parentCommentId);
        LoadingDataUtilBlack.show(CommentDetailActivity.this);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/addComment/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if(jsonObject.optString("message").equals("success")){

                                loadAfterComment();
                                int integral = jsonObject.optInt("integral");
                                mCommentListBean.setIntegral(integral+"");
                                tvNewsCommentJifen.setText(CommentDetailActivity.this.getString(R.string.news_comment_add_silver_drill,integral));
                            }
                            String str = DataParse.commentReturn(result);
                            Toast.makeText(CommentDetailActivity.this, str, Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        getCommentData();
//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LoadingDataUtilBlack.dismiss();
                        Toast.makeText(CommentDetailActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }

    /**
     * 发送评论的评论
     */
    private void postReplyComment(String replyId, String comment) {
        String userId = String.valueOf(mUser.getId());
        String nickName = mUser.getNickName();
        String parentCommentId = mCommentListBean.getCommentId();
        String newsId = newId;

        Map<String, String> map = new HashMap<>();
//        map.put("newsid", newsId);
        map.put("user", userId);
        map.put("username", nickName);
        map.put("comment", comment);
        map.put("replyid", replyId);
        map.put("parentcommentid", parentCommentId);
        LoadingDataUtilBlack.show(CommentDetailActivity.this);
        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/addCommentReply/" + newsId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if(jsonObject.optString("message").equals("success")){

                                loadAfterComment();
                                int integral = jsonObject.optInt("integral");
                                mCommentListBean.setIntegral(integral+"");
                                tvNewsCommentJifen.setText(CommentDetailActivity.this.getString(R.string.news_comment_add_silver_drill,integral));
                            }
                            String str = DataParse.commentReturn(result);
                            Toast.makeText(CommentDetailActivity.this, str, Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LoadingDataUtilBlack.dismiss();
                        Toast.makeText(CommentDetailActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
//                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }

    /**
     * 发送评论后加载新评论列表
     */
    public void loadAfterComment() {
        commentPage = 1;
        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        //请求网络数据
        Map<String, String> map = new HashMap<>();
        map.put("user", String.valueOf(mUser.getId()));
        map.put("showPage", "1");
        map.put("pageNum", "5");
        map.put("parentcommentid", parentCommentId);

        NewsRequestManager.getInstance(this).requestAsyn(TAG,"comment/loadCommentReply/" + newId, 2, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        List<CommentReplyBean> mCommentList = DataParse.getCommentReply(result);
                        if (mCommentList != null&&mCommentList.size()!=0) {
                            //将回复的数据添加到commentListBean中
                            CommentReplyBean replyBean = mCommentList.get(0);
                            setCommentListBean(replyBean);
                            commentSign.setText(ResStringUtil.getString(R.string.detail_all_comment));
//                            mCommentAdapter.refresh(mCommentList);
                            mList.clear();
                            mList.addAll(mCommentList);
                            mDetailCommentAdapter.notifyDataSetChanged();
//                            LogUtils.d(TAG, result);
                        }
//                        LogUtils.d(TAG, result);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        LogUtils.d(TAG, errorMsg);
                    }
                });
    }

    /**
     * 获取头像
     *
     * @param url
     * @param img
     */
    private void setNetPicture(String url, final ImageView img) {
        Glide
                .with(this)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade())
                .apply(new RequestOptions().placeholder(R.mipmap.default_userhead)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .transform(new CircleCrop()))
                .into(img);
    }


    /**
     * 是否支持积分显示
     */
    private void isSupportIntegral() {
        if(EnvSupportManager.isSupportShowIntergral()){
            ivNewsCommentIconJifen.setVisibility(View.VISIBLE);
            tvNewsCommentJifen.setVisibility(View.VISIBLE);
            tvLikeCount.setVisibility(View.VISIBLE);
        }else {
            ivNewsCommentIconJifen.setVisibility(View.GONE);
            tvNewsCommentJifen.setVisibility(View.GONE);
            tvLikeCount.setVisibility(View.GONE);
        }
    }

    /**
     * 是否点赞
     */
    private void isLike(){
        if (mCommentListBean.getUserDigg().equals("1")) {
            Drawable drawable = getResources().getDrawable(R.drawable.good_checked);
            // 设置边界
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvLikeCount.setCompoundDrawables(drawable,null,null,null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.good);
            // 设置边界
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvLikeCount.setCompoundDrawables(drawable,null,null,null);
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("commentBean", mCommentListBean);
        intent.putExtra("newsId", newId);
        intent.putExtra("user", mUser);
        setResult(RESULT_OK,intent);
        super.finish();
    }

    /**
     * 评论后添加到传过来页面的commentListBean中，然后传回上个页面
     * ，更新上个页面集合中的数据，不再重新请求，防止上个页面评论区位置变化
     * @param replyBean 回复的数据体
     */
    private void setCommentListBean( CommentReplyBean replyBean){
        CommentListBean.replyComment replyComment = new CommentListBean.replyComment();
        replyComment.setDate(replyBean.getDate());
        replyComment.setDiggCount(replyBean.getDiggCount());
        replyComment.setId(replyBean.getId());
        replyComment.setText(replyBean.getText());
        replyComment.setUserId(replyBean.getUserId());
        replyComment.setUserName(replyBean.getUserName());
        mCommentListBean.getReplyList().add(0,replyComment);
        mCommentListBean.setReplyCount((Integer.valueOf(mCommentListBean.getReplyCount())+1)+"");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewsRequestManager.getInstance(this).cannelOkHttpRequest(TAG);
    }
}
